package org.learn.mq.rabbit;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 接收rabbitmq的消息
 *
 * @author xianglujun
 * @date 2019/7/8 15:28
 */
public class Recv {

    private static final String QUEUE_NAME = "hello";

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.172.128");

        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            // 输出信息
            System.out.println("[*] waiting for messages, To exit process CTRL+C");

            // 定义回调类, 消息是通过server端执行push操作, 将消息推送到客户端,
            // 客户端通过在接收到消息回调的方式, 对消息进行处理
            DeliverCallback deliverCallback = (consumerTag, message) -> {
                String recvMsg = new String(message.getBody(), "utf-8");
                System.out.println("[x] received '" + recvMsg + "'");
            };

            channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
